package zzh.com.kangkenuo.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 文件数据的保存、读取静态类
 */

public class TotalFunction {
    // 取 得 外部的存储目录+/.AppFruit
    public final static String ALBUM_PATH = Environment
            .getExternalStorageDirectory() + "/.AppFruit";

    /**
     * 保存数据
     */
    static public void WriteData(Context context, String what, String info) {
        try { // userinfo
            // 一种轻型的数据存储方式，它的本质是基于XML文件存储key-value键值对数据，通常用来存储一些简单的配置信息
            SharedPreferences mySharedPreferences = context
                    .getSharedPreferences("data", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = mySharedPreferences.edit();
            editor.putString(what, info);
            editor.commit();
        } catch (Exception ex) {
        }
    }


    /**
     * 读取数据
     */
    static public String ReadData(Context context, String what) {
        if (what.equals("") || what == null)
            return null;
        try {
            SharedPreferences sharedPreferences = context.getSharedPreferences(
                    "data", Activity.MODE_PRIVATE);
            return sharedPreferences.getString(what, null); // 不存在就返回null//
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 移除数据
     */
    static public void RemoveDataAll(Context context) {
        SharedPreferences mySharedPreferences = context.getSharedPreferences(
                "data", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.clear();
        editor.commit();
    }


    /**
     * 移除数据
     */
    static public void RemoveData(Context context, String what) {
        SharedPreferences mySharedPreferences = context.getSharedPreferences(
                "data", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.remove(what);
        editor.commit();
    }


    /**
     * 移除数据
     */
    static public void RemoveTimeData(Context context, String what) {
        SharedPreferences mySharedPreferences = context.getSharedPreferences(
                "data", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.remove(what);
        editor.commit();
    }

    static public Bitmap compressBmpFromBmp(Bitmap image) { // 压缩图片
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        while (baos.toByteArray().length / 1024 > 50) {
            baos.reset();
            options -= 10;
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    static public String GetUid(Context context) {
        try {
            return ReadData(context, "uinfo").split("※")[2];
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 保存文件
     */
    static public void saveFile(Bitmap image, String fileName) // 保存图片到SD卡
    {
        File dirFile = new File(ALBUM_PATH);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
                baos.reset();// 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(
                    baos.toByteArray());
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
            newOpts.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
            newOpts.inJustDecodeBounds = false;
            int w = newOpts.outWidth;
            int h = newOpts.outHeight;
            // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
            float hh = 800f;// 这里设置高度为800f
            float ww = 480f;// 这里设置宽度为480f
            // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
            int be = 1;// be=1表示不缩放
            if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
                be = (int) (newOpts.outWidth / ww);
            } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
                be = (int) (newOpts.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            newOpts.inSampleSize = be;// 设置缩放比例
            // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
            isBm = new ByteArrayInputStream(baos.toByteArray());
            bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);

            bitmap = compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
            // bitmap=getRoundedCornerBitmap(bitmap,20);//圆角

            File myCaptureFile = new File(ALBUM_PATH + "/" + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(myCaptureFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); //
            bos.flush();
            bos.close();
        } catch (Exception e) {
            Log.e("保存图片出错", e.toString());
        }
    }

    // 获得圆角图片
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(output); // 绘画类
        final int color = 0xff424242;
        final Paint paint = new Paint(); // 绘画
        // 1、精度不一样，Rect是使用int类型作为数值，RectF是使用float类型作为数值
        // 2、两个类型提供的方法也不是完全一致
        final Rect rect = new Rect(0, 0, w, h); // 矩形
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);// 抗锯齿方法两种true
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    private static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
            if (options == 0) {
                break;
            }
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 读取文件
     */
    static public Bitmap GetBMP(String PicName) // 获取本地图片
    {
        Bitmap bitmap = null;
        String path = ALBUM_PATH + "/" + PicName;
        File mFile = new File(path);
        // 若该文件存在
        if (mFile.exists()) {
            try {
                BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
                bitmapFactoryOptions.inPurgeable = true;// 如果 inPurgeable
                // 设为True的话表示使用BitmapFactory创建的Bitmap
                // ，用于存储Pixel的内存空间在系统内存不足时可以被回收，
                bitmapFactoryOptions.inInputShareable = true;
                bitmap = BitmapFactory.decodeFile(path, bitmapFactoryOptions);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                if (baos.toByteArray().length / 1024 > 200) {// 判断如果图片大于200k,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                    bitmap = BitmapFactory.decodeFile(path, options);
                }
            } catch (Exception ex) {
                Log.e("读取图片出错", ex.toString());
            }
            return bitmap;
        } else
            return null;
    }

    static public File GetFile(String PicName) // 获取本地图片
    {
        return new File(ALBUM_PATH + "/" + PicName);
    }

    static public boolean deleteFile(String PicName) {
        String path = ALBUM_PATH + "/" + PicName;
        File file = new File(path);
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    static public byte[] getBitmapByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    static public Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return null;
        }
    }

    static public Bitmap GetBMP(String path, int flag) // 获取本地图片
    {
        Bitmap bitmap = null;
        File mFile = new File(path);
        // 若该文件存在
        if (mFile.exists()) {
            bitmap = BitmapFactory.decodeFile(path);
            /*
             * BufferedOutputStream bos; try { bos = new
			 * BufferedOutputStream(new FileOutputStream(mFile));
			 * bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); //图片压缩80%
			 * bos.flush(); bos.close(); } catch (FileNotFoundException e) {
			 * e.printStackTrace(); } catch (IOException e) {
			 * e.printStackTrace(); }
			 */
            return bitmap;
        } else
            return null;
    }

    static public Bitmap compressImageFromFile(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;// 只读边,不读内容
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 800f;//
        float ww = 480f;//
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置采样率
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;
    }

    /**
     * 从网络获取图片
     */
    static public Bitmap getUrlImage(Context context, String Path) { // 从服务器获取图片
        Bitmap img = null;
        try {
            // 获得连接
            URL url = new URL(Path); // 使用完整路径转换为Url
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(6000);// 设置超时
            conn.setDoInput(true);
            conn.setUseCaches(false);// 不缓存
            conn.connect();
            InputStream is = conn.getInputStream();// 获得图片的数据流
            byte[] data = readStream(is);
            if (data != null) {
                img = BitmapFactory.decodeByteArray(data, 0, data.length);
            }
            // img = BitmapFactory.decodeStream(is);
            is.close();
            return img;
        } catch (Exception e) {
            Log.e("下载图片出错", e.toString());
            // return
            // ((BitmapDrawable)context.getResources().getDrawable(R.drawable.home_f1)).getBitmap();
            return null;
        }
    }

    static public Uri getURI(String FileName) {
        try {
            File file = new File(ALBUM_PATH + "/" + FileName);
            return Uri.fromFile(file);// 通过文件创建一个uri
        } catch (Exception ex) {
            return null;
        }

    }

    /*
     * 从网络上获取图片，如果图片在本地存在的话就直接拿，如果不存在再去服务器上下载图片 这里的path是图片的地址
     */
    static public Uri getImageURI(String Path, String FileName)
            throws Exception {
        try {
            // String name = path.substring(path.lastIndexOf("."));
            File file = new File(ALBUM_PATH + "/" + FileName);
            // 如果图片存在本地缓存目录，则不去服务器下载
            /*
             * if (file.exists()) { return
			 * Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI } else {
			 */
            // 从网络上获取图片
            URL url = new URL(Path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);// 连接超时
            conn.setRequestMethod("GET");// 请求方式
            conn.setDoInput(true);
            if (conn.getResponseCode() == 200) {

                InputStream is = conn.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
                // 返回一个URI对象
                return Uri.fromFile(file);
            } else {
                Log.e("下载图片出错", String.valueOf(conn.getResponseCode()));
                return null;
            }

            // }
        } catch (Exception e) {
            Log.e("下载图片出错", e.toString());
            return null;
        }
    }

    static public String[] StrToArray(String re) { // 祛除获取的数据中的多余字符 并返回字符串数组
        try {
            re = re.replace("\"", "");
            re = re.replace("\\", "");
            re = re.replace("{", "");
            re = re.replace("}", "");
            re = re.replace("[", "");
            re = re.replace("]", "");
            return re.split("\\:|,");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param re
     * @return
     * @describe 新服务器获取JSON字符转JSON对象
     */
    static public JSONObject StrToObject(String re) {
        try {
            return new JSONObject(re);
        } catch (Exception e) {
            return null;
        }
    }

    /*
     * 得到图片字节流 数组大小
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

}
